import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/components/calendar_btn_icon.dart';
import 'package:share_fit/app/components/date_type_bar.dart';
import 'package:share_fit/app/components/table_calendar_dialog.dart';
import 'package:share_fit/app/controllers/home/sleep/components/sleep_bar_chart.dart';
import 'package:share_fit/app/controllers/home/sleep/components/sleep_stacked_chart.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/date_type_enum.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'logic.dart';

class SleepPage extends StatelessWidget {
  SleepPage({super.key});

  final logic = Get.find<SleepLogic>();
  final state = Get.find<SleepLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackBtnIcon(onTap: () => logic.goBack()),
        actions: [
          GetBuilder<SleepLogic>(
            id: 'calendar_btn_icon',
            builder: (ctrl) {
              return ctrl.state.selectedDateType.value == DateType.day
                  ? CalendarBtnIcon(
                      calenderDay: ctrl.state.selectedDate,
                      onTap: () => _showDatePicker(context),
                    )
                  : Container();
            },
          ),
        ],
      ),
      body: Container(
        padding: EdgeInsets.only(left: 40.w, right: 40.w),
        child: ListView(
          children: [
            SizedBox(height: 59.h),
            GetBuilder<SleepLogic>(
              id: 'date_type_bar',
              builder: (ctrl) => DateTypeBar(
                initIndex: ctrl.state.dateTypeBarIndex,
                onSelectChanged: (index, dateType) => ctrl.changeDateType(selectedIndex: index, type: dateType),
              ),
            ),
            SizedBox(height: 59.h),
            _buildCalendarContainer(),
            SizedBox(height: 60.h),
            _buildChartContainer(),
            _buildAnalysisContainer(),
            _buildNapsContainer(),
            SizedBox(height: 60.h),
            _buildQualityContainer(),
            SizedBox(height: 79.h),
          ],
        ),
      ),
    );
  }

  _buildCalendarContainer() {
    return GetBuilder<SleepLogic>(
      id: 'sleep_date_range',
      builder: (ctrl) => Container(
        alignment: Alignment.center,
        child: Text(ctrl.state.dateRangeText),
      ),
    );
  }

  _buildQualityContainer() {
    return GetBuilder<SleepLogic>(
      id: 'sleep_analysis',
      builder: (ctrl) => Container(
        padding: EdgeInsets.symmetric(vertical: 50.w, horizontal: 55.w),
        decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
        child: !state.dataList.any((e) => (e.sleepTime ?? 0) > 0)
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(LocaleKeys.sleep_quality_title.ts, style: TextStyle(fontSize: 48.sp)),
                  SizedBox(height: 15.h),
                  Divider(color: Colors.grey.withOpacity(.3)),
                  SizedBox(height: 120.h),
                  Center(child: Image.asset('assets/images/home/empty.png', width: 300.w, height: 300.w)),
                  SizedBox(height: 120.h),
                ],
              )
            : Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(LocaleKeys.sleep_quality_title.ts, style: TextStyle(fontSize: 48.sp)),
                  SizedBox(height: 15.h),
                  Divider(color: Colors.grey.withOpacity(.3)),
                  SizedBox(height: 15.h),
                  Row(
                    children: [
                      Image.asset('assets/images/home/sleep_late.png', width: 60.h, height: 60.h),
                      SizedBox(width: 25.h),
                      Text(LocaleKeys.sleep_late_title.ts, style: TextStyle(fontSize: 48.sp)),
                    ],
                  ),
                  SizedBox(height: 35.h),
                  Text(LocaleKeys.sleep_late_description_text.ts),
                  SizedBox(height: 35.h),
                  Row(
                    children: [
                      Image.asset('assets/images/home/sleep_lack.png', width: 60.h, height: 60.h),
                      SizedBox(width: 25.h),
                      Text(LocaleKeys.sleep_less_title.ts, style: TextStyle(fontSize: 48.sp)),
                    ],
                  ),
                  SizedBox(height: 35.h),
                  Text(LocaleKeys.sleep_less_description_text.ts),
                ],
              ),
      ),
    );
  }

  _buildNapsContainer() {
    return GetBuilder<SleepLogic>(
      id: 'naps_container',
      builder: (ctrl) => state.selectedDateType.value != DateType.day || state.napList.isEmpty
          ? Container()
          : Container(
              margin: EdgeInsets.only(top: 60.h),
              padding: EdgeInsets.symmetric(vertical: 50.w, horizontal: 55.w),
              decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
              child: Column(
                children: [
                  Text(LocaleKeys.sleep_nap_desc_text.ts),
                  SizedBox(height: 25.h),
                  Divider(color: Colors.grey.withOpacity(.3)),
                  SizedBox(height: 35.h),
                  state.napList.isEmpty
                      ? Text(LocaleKeys.no_records_text.ts)
                      : ListView(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          children: _buildNapItems(),
                        ),
                ],
              ),
            ),
    );
  }

  _buildNapItems() {
    return ListTile.divideTiles(
        color: Colors.grey,
        tiles: state.napList
            .map(
              (item) => ListTile(
                title: Text(LocaleKeys.sleep_naps_text.ts, style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                subtitle: Text(item.napTimeRangeText, style: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 42.sp)),
                trailing: SizedBox(
                  width: 380.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(item.formatNapTimeText, style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                      const Icon(Icons.keyboard_arrow_right, size: 30),
                    ],
                  ),
                ),
                dense: true,
                onTap: () => logic.goNapSleepPage(model: item),
              ),
            )
            .toList());
  }

  List<PieChartSectionData> showingSections() {
    int total = state.sleepSumWithoutAwake;
    double width = 40.w;
    if (state.isPieChartDataIsNotEmpty) {
      return [
        PieChartSectionData(radius: width, color: Colors.grey.withOpacity(.3), value: 25, title: ''),
        PieChartSectionData(radius: width, color: Colors.grey.withOpacity(.3), value: 25, title: ''),
        PieChartSectionData(radius: width, color: Colors.grey.withOpacity(.3), value: 25, title: ''),
        PieChartSectionData(radius: width, color: Colors.grey.withOpacity(.3), value: 25, title: ''),
      ];
    }

    double ds = state.deepSleepSum / total * 100;
    double ls = state.lightSleepSum / total * 100;
    double awake = state.awakeSleepSum / total * 100;
    double rem = state.remSleepSum / total * 100;

    return [
      PieChartSectionData(radius: width, color: state.deepSleep.$2, value: ds, title: ''),
      PieChartSectionData(radius: width, color: state.lightSleep.$2, value: ls, title: ''),
      PieChartSectionData(radius: width, color: state.rem.$2, value: rem, title: ''),
      PieChartSectionData(radius: width, color: state.awake.$2, value: awake, title: ''),
    ];
  }

  _buildAnalysisContainer() {
    return GetBuilder<SleepLogic>(
      id: 'sleep_analysis',
      builder: (ctrl) => !state.dataList.any((e) => (e.sleepTime ?? 0) > 0)
          ? Container()
          : Container(
              margin: EdgeInsets.only(top: 60.h),
              padding: EdgeInsets.symmetric(vertical: 50.w, horizontal: 35.w),
              decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      SizedBox(
                        width: 400.w,
                        child: Stack(
                          children: [
                            AspectRatio(
                              aspectRatio: 1,
                              child: PieChart(
                                PieChartData(
                                  borderData: FlBorderData(show: false),
                                  sectionsSpace: ctrl.state.isPieChartDataIsNotEmpty ? 0 : 5.w,
                                  centerSpaceRadius: 130.w,
                                  sections: showingSections(),
                                ),
                              ),
                            ),
                            Positioned(top: 140.w, left: 160.w, child: Text(LocaleKeys.sleep_ratio_text.ts, style: TextStyle(fontSize: 42.sp))),
                          ],
                        ),
                      ),
                      SizedBox(width: 10.h),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      width: 30.w,
                                      height: 30.w,
                                      decoration: BoxDecoration(color: state.deepSleep.$2, borderRadius: BorderRadius.all(Radius.circular(50.r))),
                                    ),
                                    SizedBox(width: 20.w),
                                    SizedBox(
                                      width: 300.w,
                                      child: Text(ctrl.getDeepSleepTitle(), style: TextStyle(fontSize: 43.sp, overflow: TextOverflow.ellipsis)),
                                    ),
                                  ],
                                ),
                                Text(ctrl.state.deepSleepSumText, style: TextStyle(fontSize: 43.sp)),
                              ],
                            ),
                            SizedBox(height: 20.h),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      width: 30.w,
                                      height: 30.w,
                                      decoration: BoxDecoration(color: state.lightSleep.$2, borderRadius: BorderRadius.all(Radius.circular(50.r))),
                                    ),
                                    SizedBox(width: 20.w),
                                    SizedBox(
                                      width: 300.w,
                                      child: Text(ctrl.getLightSleepTitle(), style: TextStyle(fontSize: 43.sp, overflow: TextOverflow.ellipsis)),
                                    ),
                                  ],
                                ),
                                Text(ctrl.state.lightSleepSumText, style: TextStyle(fontSize: 43.sp)),
                              ],
                            ),
                            SizedBox(height: 20.h),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      width: 30.w,
                                      height: 30.w,
                                      decoration: BoxDecoration(color: state.rem.$2, borderRadius: BorderRadius.all(Radius.circular(50.r))),
                                    ),
                                    SizedBox(width: 20.w),
                                    Text(ctrl.getRemSleepTitle(), style: TextStyle(fontSize: 43.sp, overflow: TextOverflow.ellipsis)),
                                  ],
                                ),
                                Text(ctrl.state.remSleepSumText, style: TextStyle(fontSize: 43.sp)),
                              ],
                            ),
                            SizedBox(height: 20.h),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      width: 30.w,
                                      height: 30.w,
                                      decoration: BoxDecoration(color: state.awake.$2, borderRadius: BorderRadius.all(Radius.circular(50.r))),
                                    ),
                                    SizedBox(width: 20.w),
                                    Text(ctrl.getAwakeTitle(), style: TextStyle(fontSize: 43.sp)),
                                  ],
                                ),
                                Text(ctrl.state.awakeSleepSumText, style: TextStyle(fontSize: 43.sp)),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 60.h),
                  Row(
                    children: [
                      SizedBox(width: 30.h),
                      Text(LocaleKeys.sleep_analysis_title.ts, style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                    ],
                  ),
                  SizedBox(height: 30.h),
                  ListView(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    children: ListTile.divideTiles(
                      color: Colors.grey,
                      tiles: [
                        ListTile(
                          title: Text(
                            '${ctrl.getTotalDurationText()}${state.sleepSumWithoutNapsAndAwakeText}',
                            style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp),
                          ),
                          subtitle:
                              Text(LocaleKeys.sleep_total_ref_value_text.ts, style: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 42.sp)),
                          trailing: SizedBox(
                            width: 280.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                state.totalRefValueLevelText,
                                const Icon(Icons.keyboard_arrow_right, size: 30),
                              ],
                            ),
                          ),
                          dense: true,
                          onTap: () => logic.goSleepDurationPage(),
                        ),
                        ListTile(
                          title: Text(ctrl.getDeepSleepRatioText(), style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                          subtitle: Text(LocaleKeys.sleep_deep_ratio_ref_value_text.ts,
                              style: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 42.sp)),
                          trailing: SizedBox(
                            width: 280.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                state.dsRefValueLevelText,
                                const Icon(Icons.keyboard_arrow_right, size: 30),
                              ],
                            ),
                          ),
                          dense: true,
                          onTap: () => logic.goDeepSleepPage(),
                        ),
                        ListTile(
                          title: Text(ctrl.getLightSleepRatioText(), style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                          subtitle: Text(LocaleKeys.sleep_light_ratio_ref_value_text.ts,
                              style: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 42.sp)),
                          trailing: SizedBox(
                            width: 280.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                state.lsRefValueLevelText,
                                const Icon(Icons.keyboard_arrow_right, size: 30),
                              ],
                            ),
                          ),
                          dense: true,
                          onTap: () => logic.goLightSleepPage(),
                        ),
                        ListTile(
                          title: Text(ctrl.getRemSleepRatioText(), style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                          subtitle: Text(LocaleKeys.sleep_rem_ratio_ref_value_text.ts,
                              style: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 42.sp)),
                          trailing: SizedBox(
                            width: 280.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                state.remRefValueLevelText,
                                const Icon(Icons.keyboard_arrow_right, size: 30),
                              ],
                            ),
                          ),
                          dense: true,
                          onTap: () => logic.goRemSleepPage(),
                        ),
                        ListTile(
                          title: Text(ctrl.getAwakeRatioText(), style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                          subtitle: Text(LocaleKeys.sleep_awake_times_ref_value_text.ts,
                              style: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 42.sp)),
                          trailing: SizedBox(
                            width: 280.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                state.awakeRefValueLevelText,
                                const Icon(Icons.keyboard_arrow_right, size: 30),
                              ],
                            ),
                          ),
                          dense: true,
                          onTap: () => logic.goAwakeSleepPage(),
                        ),
                        if (state.selectedDateType.value != DateType.day)
                          ListTile(
                            title: Text(ctrl.getNapRatioText(), style: TextStyle(color: Colors.black.withOpacity(0.6), fontSize: 48.sp)),
                            trailing: SizedBox(
                              width: 350.w,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Text(state.napsSleepSumText, style: TextStyle(fontSize: 48.sp)),
                                  const Icon(Icons.keyboard_arrow_right, size: 30),
                                ],
                              ),
                            ),
                            dense: true,
                            onTap: () => logic.goNapSleepPage(model: null),
                          ),
                      ],
                    ).toList(),
                  ),
                ],
              ),
            ),
    );
  }

  Widget _buildSummary() {
    return GetBuilder<SleepLogic>(
      id: 'sleep_summary',
      builder: (_) {
        return Container(
          constraints: BoxConstraints.expand(height: 250.w),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(LocaleKeys.widgets_sleep.ts, style: TextStyle(fontSize: 48.sp)),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.baseline,
                textBaseline: TextBaseline.alphabetic,
                children: [
                  Text(_.state.sleepSummary.sleepSumH.toString(), style: TextStyle(fontSize: 120.sp)),
                  Baseline(
                    baseline: 20.0,
                    baselineType: TextBaseline.alphabetic,
                    child: Text(LocaleKeys.time_unit_hour.ts, style: TextStyle(fontSize: 80.sp, color: Colors.grey.withOpacity(0.8))),
                  ),
                  Text(_.state.sleepSummary.sleepSumM.toString(), style: TextStyle(fontSize: 120.sp)),
                  Baseline(
                    baseline: 20.0,
                    baselineType: TextBaseline.alphabetic,
                    child: Text(LocaleKeys.time_unit_minute.ts, style: TextStyle(fontSize: 80.sp, color: Colors.grey.withOpacity(0.8))),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildChartContainer() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 50.w, horizontal: 55.w),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
      child: GetBuilder<SleepLogic>(
        id: 'sleep_bar_chart',
        builder: (ctrl) {
          return SizedBox(
            width: 1.sw,
            height: 450.h,
            child: ctrl.state.selectedDateType.value == DateType.day
                ? SleepBarChart(items: state.barChartDataList)
                : SleepStackedChart(
                    summaryList: state.sleepSummaries,
                    dateType: state.selectedDateType.value,
                  ),
          );
        },
      ),
    );
  }

  /// 点击右上角日历图标，打开日历选择
  _showDatePicker(BuildContext context) {
    Get.dialog(
      TableCalendarDialog(
        onEvenLoad: (day) => logic.onCalendarEventLoad(day),
      ),
      barrierColor: Colors.black.withOpacity(.8),
    ).then((value) => logic.datePicker(value));
  }
}
